'use strict';
define(function(require,exports,module){

  var $ = require('jquery');
  var Chat = function(){
    this.socket = null;
    this.modal = null;
  }

  Chat.prototype = {
    _showMsg:function(nickname,msg,color){
      var contentContainer = document.getElementById('content');
      var msgContainer = document.createElement('p');
      var date = new Date().toTimeString().substr(0,8);
      msgContainer.style.color = color || '#000';
      msgContainer.innerHTML = nickname + ' <span class="timestamp">['+date+']:</span> '+msg;
      contentContainer.appendChild(msgContainer);
      contentContainer.scrollTop = contentContainer.scrollHeight;
    },
    _showLogin:function(){
      var self = this;
      $('#gridSystemModal').modal('show');
      $('#gridSystemModal').on('shown.bs.modal', function () {
        $('#nickname').focus();
        self.modal = $(this);
      })
    },
    _hideLogin:function(){
      $('#gridSystemModal').modal('hide');
    },
    init:function(){
      var self = this;
      self.socket = io();
      self.socket.on('connect',function(){
        self._showLogin();
        $('#error_nickname').text('');
        $('#nickname').focus();
      });

      //监听昵称存在的情况
      self.socket.on('nickExisted',function(){
        $('#error_nickname').text('昵称已经存在！请换一个吧!');
      });

      //监听昵称不存在，登录成功
      self.socket.on('loginSuccess',function(){
        self._hideLogin();
        $('title').text($('#nickname').val() + ' - 欢迎加入聊天室');
      });

      //系统监测
      self.socket.on('system',function(nickname,userCount,type){
        var msg = nickname + (type == 'login' ? ' joined' : ' leave');
        self._showMsg('system',msg,'red');
        $('#status').html(' <span class="label label-success">'+userCount+'个用户在线</span>');
      });

      //显示提交的信息
      self.socket.on('newMsg',function(nickname,msg){
        self._showMsg(nickname,msg);
      });

      //设置昵称操作
      $('#send_nick').click(function(){
        var nickname = $('#nickname').val();
        if(nickname.trim().length != 0){
          self.socket.emit('login',nickname);
        }else{
          $('#nickname').focus();
        }
      });

      //发送消息
      document.getElementById('send').addEventListener('click',function(){
        var text = document.getElementById('text').value;
        if(text.trim().length != 0){
          self.socket.emit('send',text);
          self._showMsg('ME',text);
          document.getElementById('text').value = '';
          document.getElementById('text').focus();
        }else{
          document.getElementById('text').focus();
        }
      })
    }
  }

  module.exports = Chat;
});